package com.ourcauser.worn.controllers;

import java.util.Date;
import java.util.List;
import java.util.UUID;

import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.ObjectMessage;
import javax.jms.Session;
import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.jms.core.MessageCreator;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.ourcauser.worn.entities.FuncTrace;
import com.ourcauser.worn.forms.FuncTraceForm;
import com.ourcauser.worn.services.IFuncTraceService;

@Controller
public class LocationController {

	@Value("#{messagesProperties['FuncForm.ip.repeat']}")
	private String ipRepeat;
	
	@Autowired
	@Qualifier("funcTraceService")
	private IFuncTraceService funcTraceService;
	
	@Autowired
	private JmsTemplate jmsTemplate;
	
	
	// 进入页面
	@GetMapping("/funcTrace")
	public String voteFunc(@ModelAttribute("funcTraceForm") FuncTraceForm funcTraceForm, Model model){
		
		String groupID = UUID.randomUUID().toString();
		
		funcTraceForm.setGroupID(groupID);
		
		return "funcTrace";		
	}
	
	// 提交记录
	@PostMapping("/funcTrace")
	public String voteFunc(@Valid FuncTraceForm funcTraceForm,
			HttpServletRequest request,
			BindingResult result, Model model){
		
		// 1. 页面验证
		if (result.hasErrors()) {		
			return "funcTrace";	
		}		
		
		// 2. 保存记录
		String IP = getIP(request);
		if(!IP.isBlank()) {
			
			int cunt = funcTraceService.checkForInsert(IP);
			
			if(cunt==0) {
				
				// 2.1 拼凑数据 
				String groupID = funcTraceForm.getGroupID().toString();
				
				FuncTrace funcTrace = new FuncTrace();
				funcTrace.setIP(IP);
				funcTrace.setGroupID(groupID);
				funcTrace.setLatitude("");
				funcTrace.setLongitude("");
				funcTrace.setOperateDateTime(new Date());
				funcTrace.setPkey(UUID.randomUUID().toString());
		
				
				// 2.2 保存数据
		        jmsTemplate.send(new MessageCreator() {
		            
		            public Message createMessage(Session session) throws JMSException {
		            	
		            	ObjectMessage msg = session.createObjectMessage(funcTrace);
		            	
		                return msg;
		            }
		        });				
				
			}else {
				result.addError(new FieldError("funcTraceForm", "pkey", ipRepeat));
				return "funcTrace";
			}
			
		}
		
		model.addAttribute("optResult", "success");
		
		return "funcTrace";	
	}
	
	// 保存页面所获取的地理位置
	@PostMapping("/savePageLocat")
	public @ResponseBody String savePageLocat(String position,String groupID){
		
		String result = "";
		
		int pos = position.indexOf(",");		
		
		if(pos > 0) {
			
			String lng = position.substring(0, pos);
			String lat = position.substring(pos+1);
			
			FuncTrace funcTrace = new FuncTrace();
			funcTrace.setIP("");
			funcTrace.setGroupID(groupID);
			funcTrace.setLatitude(lat);
			funcTrace.setLongitude(lng);
			funcTrace.setOperateDateTime(new Date());
			funcTrace.setPkey(UUID.randomUUID().toString());
			
			funcTraceService.insert(funcTrace);
			
			result = "success";
		}else
			result = "fail";
		
		return result;
	}
	
	// 进入地址列表页面
	@GetMapping("/viewFuncTrace")
	public String viewFuncTrace(Model model){
		
		List<FuncTrace> lstFuncTrace = funcTraceService.getDatas();
		
		model.addAttribute("funcTraces", lstFuncTrace);
		
		return "viewFuncTrace";	
	}
	
	// 进入地址列表页面
	@GetMapping("/viewFuncTraceLocat")
	public String viewFuncTraceLocate(@RequestParam(value="pkey", required = true) String pkey, Model model){
				
		FuncTrace funcTrace = funcTraceService.getDataByPkey(pkey);
		
		model.addAttribute("lng", funcTrace.getLongitude().toString());
		model.addAttribute("lat", funcTrace.getLatitude().toString());
		
		return "viewFuncTraceLocat";
	}
	
	// 获取 IP
	public String getIP(HttpServletRequest request) {		
		String remoteAddr = "";		
        if (request != null) {
            remoteAddr = request.getHeader("X-FORWARDED-FOR");
            if (remoteAddr == null || "".equals(remoteAddr)) {
                remoteAddr = request.getRemoteAddr();
            }
        }        
        return remoteAddr;
	}
	
}
